<!-- 课程章节 -->
<template>
    <div>
        <el-button type="success" @click="openChapterDialog()">添加章节</el-button>

        <ul class="chanpterList">
            <draggable
                :list="chapters"
                group="chapter"
                @start="onStart"
                @end="onEnd"
                animation="300"
                ghost-class="ghost"
                chosen-class="chosen"
            >
                <transition-group>
                    <li v-for="chapter in chapters" :key="chapter.id">
                        <p>
                            {{ chapter.title }}
                            <span class="acts">
                                <el-button type="text" @click="openVideoDialog(chapter.id)">添加小节</el-button>
                                <el-button
                                    style
                                    type="text"
                                    @click="openChapterDialog(chapter.id)"
                                >编辑</el-button>
                                <el-button type="text" @click="deleteChapter(chapter.id)">删除</el-button>
                            </span>
                        </p>

                        <!-- 小节 -->
                        <ul class="chanpterList videoList">
                            <draggable
                                :list="chapter.children"
                                group="video"
                                @start="onStart"
                                @end="onEnd"
                                animation="300"
                                ghost-class="ghost"
                                chosen-class="chosen"
                            >
                                <transition-group>
                                    <li v-for="videoItem in chapter.children" :key="videoItem.id">
                                        <p>
                                            {{ videoItem.title }}
                                            <span class="acts">
                                                <el-button
                                                    type="text"
                                                    @click="openVideoDialog(chapter.id,videoItem.id)"
                                                >编辑</el-button>
                                                <el-button
                                                    type="text"
                                                    @click="deleteVideo(videoItem)"
                                                >删除</el-button>
                                            </span>
                                        </p>
                                    </li>
                                </transition-group>
                            </draggable>
                        </ul>
                    </li>
                </transition-group>
            </draggable>
        </ul>

        <!--************************************添加修改章节对话框*****************************************-->
        <el-dialog
            title="章节"
            :visible.sync="dialogChapterVisible"
            width="40%"
            :before-close="closeChapterDialog"
        >
            <el-form :model="chapter">
                <el-form-item label="章节标题">
                    <el-input v-model="chapter.title" autocomplete="off" style="width:50%"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="closeChapterDialog()">取 消</el-button>
                <el-button type="primary" @click="saveOrUpadteChapter()">确 定</el-button>
            </div>
        </el-dialog>

        <!--************************************添加修改小节对话框*****************************************-->
        <el-dialog
            title="小节"
            :visible.sync="dialogVideoVisible"
            width="40%"
            :before-close="closeVideoDialog"
        >
            <el-form :model="video">
                <el-form-item label="小节标题">
                    <el-input v-model="video.title" autocomplete="off" style="width:50%"></el-input>
                </el-form-item>
                <el-form-item label="是否免费">
                    <el-switch v-model="video.isFree" active-text="免费" inactive-text="付费"></el-switch>
                </el-form-item>
                <el-form-item label="上传视频">
                    <el-upload
                        :on-success="handleVodUploadSuccess"
                        :on-remove="handleVodRemove"
                        :before-remove="beforeVodRemove"
                        :on-exceed="handleUploadExceed"
                        :on-progress="fileUploading"
                        :file-list="fileList"
                        :action="BASE_API"
                        :limit="1"
                        class="upload-demo"
                    >
                        <el-button size="small" type="primary">上传视频</el-button>
                        <el-tooltip placement="right-end">
                            <div slot="content">
                                最大支持1G，
                                <br />支持3GP、ASF、AVI、DAT、DV、FLV、F4V、
                                <br />GIF、M2T、M4V、MJ2、MJPEG、MKV、MOV、MP4、
                                <br />MPE、MPG、MPEG、MTS、OGG、QT、RM、RMVB、
                                <br />SWF、TS、VOB、WMV、WEBM 等视频格式上传
                            </div>
                            <i class="el-icon-question" />
                        </el-tooltip>
                    </el-upload>
                </el-form-item>
                <el-form-item label="视频大小" v-if="video.videoSourceId">
                    <el-tag effect="plain">{{(video.size/1048576).toFixed(2) +" MB"}}</el-tag>
                </el-form-item>
                <el-form-item label="视频时长" v-if="video.videoSourceId">
                    <el-tag effect="plain">{{getSFM(video.duration)}}</el-tag>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="closeVideoDialog">取 消</el-button>
                <el-button type="primary" @click="saveOrUpdateVideo">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
import {
    deleteChapter,
    getChapterById,
    saveOrUpdateChapter,
    getChaptersByCourseId,
    updateChapterAndVideoSort,
} from "@/api/course/chapter";
import {
    deleteVideo,
    getVideoById,
    saveOrUpdateVideo,
} from "@/api/course/video";
import { removeBatchVideoByIds } from "@/api/course/vod";
import { Loading } from "element-ui";
import draggable from "vuedraggable";
import { getSFM } from "@/utils/timeUtils";

export default {
    //import引入的组件需要注入到对象中才能使用
    components: { draggable },
    props: ["courseId"],
    data() {
        //这里存放数据
        return {
            drag: false,
            chapters: [],
            chapterId: "",
            //添加章节或修改章节
            chapter: {
                id: "",
                courseId: "",
                title: "",
                sort: "",
            },
            //添加或修改小节
            video: {
                id: "",
                courseId: "",
                chapterId: "",
                title: "",
                videoSourceId: "",
                videoOriginalName: "",
                sort: "",
                playCount: "",
                isFree: "",
                duration: "",
                status: "",
                size: "",
            },
            dialogChapterVisible: false, //章节对话框是否出现
            dialogVideoVisible: false, //小节对话框是否出现
            BASE_API: process.env.BASE_API + "/vod/video/uploadVideo",
            fileList: [],
            loadingInstance: null,
        };
    },
    //监听属性 类似于data概念
    computed: {},
    //监控data中的数据变化
    watch: {},
    //方法集合
    methods: {
        closeChapterDialog() {
            this.chapter = {};
            this.dialogChapterVisible = false;
        },
        //打开添加章节或修改章节对话框
        openChapterDialog(chapterId) {
            if (chapterId) {
                getChapterById(chapterId).then((response) => {
                    this.chapter = response.data.chapter;
                });
            }
            this.dialogChapterVisible = true;
        },

        //添加或修改章节
        saveOrUpadteChapter() {
            this.chapter.courseId = this.courseId;
            //如果要新增，需要设置章节的排序
            if (!this.chapter.id) {
                this.chapter.sort = this.chapters.length + 1;
            }
            saveOrUpdateChapter(this.chapter).then((response) => {
                this.closeChapterDialog();
                this.getAllChapters();
                this.$message({
                    message: "保存成功",
                    type: "success",
                });
            });
        },
        getAllChapters() {
            if (this.courseId) {
                getChaptersByCourseId(this.courseId).then((response) => {
                    this.chapters = response.data.chapters;
                });
            }
        },
        deleteChapter(chapterId) {
            this.$confirm("确定要删除吗?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            })
                .then(() => {
                    deleteChapter(chapterId).then((response) => {
                        this.getAllChapters();
                        this.$message({
                            type: "success",
                            message: "删除成功!",
                        });
                    });
                })
                .catch(() => {});
        },

        //添加或修改小节
        saveOrUpdateVideo() {
            this.video.courseId = this.courseId;
            this.video.chapterId = this.chapterId;
            //如果是添加，需要设置小节的sort
            if (!this.video.id) {
                for (let i = 0; i < this.chapters.length; i++) {
                    if (this.chapters[i].id === this.video.chapterId) {
                        this.video.sort = this.chapters[i].children.length + 1;
                    }
                }
            }
            saveOrUpdateVideo(this.video).then((response) => {
                this.getAllChapters();
                this.$message({
                    message: "保存成功",
                    type: "success",
                });
                this.closeVideoDialog();
            });
        },
        openVideoDialog(chapterId, videoId) {
            this.chapterId = chapterId;
            if (videoId) {
                getVideoById(videoId).then((response) => {
                    this.video = response.data.video;
                    if (response.data.video.videoOriginalName) {
                        this.fileList = [
                            { name: response.data.video.videoOriginalName },
                        ];
                    }
                });
            }
            this.dialogVideoVisible = true;
        },
        closeVideoDialog() {
            this.video = {};
            this.fileList = [];
            this.dialogVideoVisible = false;
        },

        //删除小节
        deleteVideo(video) {
            this.$confirm("确定要删除吗?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            })
                .then(() => {
                    deleteVideo({
                        id: video.id,
                        videoSourceId: video.videoSourceId,
                    }).then((response) => {
                        this.getAllChapters();
                        this.$message({
                            type: "success",
                            message: "删除成功!",
                        });
                    });
                })
                .catch(() => {});
        },

        /**********************************************视频上传********************************************* */
        beforeVodRemove(file, fileList) {
            return this.$confirm(`确定移除 ${file.name}？`);
        },
        handleVodRemove(file, fileList) {
            removeBatchVideoByIds(this.video.videoSourceId).then((response) => {
                this.video.videoSourceId = "";
                this.video.videoOriginalName = "";
                this.fileList = [];
                this.$message({
                    type: "success",
                    message: "删除成功",
                });
            });
        },
        //上传视频成功
        handleVodUploadSuccess(response, file, fileList) {
            this.video.videoSourceId = response.data.videoId;
            this.video.duration = response.data.duration;
            this.video.videoOriginalName = file.name;
            this.video.size = file.size;
            this.fileList = fileList;
            this.$nextTick(() => {
                // 以服务的方式调用的 Loading 需要异步关闭
                Loading.service().close();
            });
        },
        //上传之前
        handleUploadExceed() {
            this.$message({
                message: "确保之前上传已删除",
                type: "warning",
            });
        },
        //文件上传是的钩子
        fileUploading(event, file, fileList) {
            Loading.service();
        },

        //根据秒获取时分秒
        getSFM(seconds) {
            return getSFM(seconds);
        },

        //列表拖拽的方法
        onStart() {
            this.drag = true;
        },
        onEnd() {
            //更新数据库
            let uploadData = [];
            //1、整理数据
            for (let i = 0; i < this.chapters.length; i++) {
                let temp = {
                    chapterId: this.chapters[i].id,
                    sort: i,
                    children: [],
                };
                let children = [];
                for (let j = 0; j < this.chapters[i].children.length; j++) {
                    children.push({
                        videoId: this.chapters[i].children[j].id,
                        sort: j,
                    });
                }
                temp.children = children;
                uploadData.push(temp);
            }
            //2、传给后端更新 主要更新的就是sort
            console.log(uploadData);
            updateChapterAndVideoSort(uploadData).then((response) => {
                this.getAllChapters();
            });
        },
    },
    //生命周期 - 创建完成（可以访问当前this实例）
    created() {
        this.getAllChapters();
    },
    //生命周期 - 挂载完成（可以访问DOM元素）
    mounted() {},
    beforeCreate() {}, //生命周期 - 创建之前
    beforeMount() {}, //生命周期 - 挂载之前
    beforeUpdate() {}, //生命周期 - 更新之前
    updated() {}, //生命周期 - 更新之后
    beforeDestroy() {}, //生命周期 - 销毁之前
    destroyed() {}, //生命周期 - 销毁完成
    activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发，页面一旦激活就会触发
};
</script>
<style scoped>
.chanpterList {
    position: relative;
    list-style: none;
    margin: 0;
    padding: 0;
}
.chanpterList li {
    position: relative;
}
.chanpterList p {
    font-size: 20px;
    margin: 10px 0;
    padding: 10px;
    height: 70px;
    line-height: 50px;
    width: 100%;
    border: 1px solid #ddd;
}
.chanpterList .acts {
    float: right;
    font-size: 14px;
}

.videoList {
    padding-left: 50px;
}
.videoList p {
    font-size: 14px;
    margin: 10px 0;
    padding: 10px;
    height: 50px;
    line-height: 30px;
    width: 100%;
    border: 1px dotted #ddd;
}
.chosen {
    background-color: rgb(76, 137, 241) !important;
    color: #fff;
}

.ghost {
    background-color: rgb(243, 126, 126) !important;
}
</style>